<template>
  <div v-title data-title="巡线拣货工作台">
    <el-row :gutter="12">
      <el-card>
        <el-table
          :data="tableData"
          border
          :row-style="{ height: '20px', 'font-size': '15px' }"
          style="width: 100%"
          :cell-style="{ padding: '0px' }"
          :header-row-style="{ height: '40px' }"
          :height="tableHeight"
          ref="tableRef"
          v-loading="loading"
          :header-cell-style="{
            height: '20px',
            padding: '0px',
            'font-size': '15px',
            background: '#18bb9c',
            color: '#fff',
            'text-align': 'center',
          }"
        >
          <el-table-column
            prop="SerialNumber"
            :width="tableHeight * 0.22"
            label="发动机序列号"
            :align="align"
          >
          </el-table-column>
          <el-table-column
            prop="Band"
            label="波段信息"
            :width="tableHeight * 0.15"
            :align="align"
          >
          </el-table-column>
          <el-table-column
            prop="FromLoc"
            label="亮灯拣货库位"
            :width="tableHeight * 0.22"
            :align="align"
          >
          </el-table-column>
          <el-table-column
            prop="FromCID"
            label="亮灯拣货托盘"
            :width="tableHeight * 0.16"
            :align="align"
          >
          </el-table-column>
          <el-table-column
            prop="QtyPlan"
            :width="tableHeight * 0.15"
            label="计划出库数"
            :align="align"
          >
          </el-table-column>
          <el-table-column
            prop="SkuId"
            :width="tableHeight * 0.2"
            label="物料编码"
            :align="align"
          >
          </el-table-column>
          <el-table-column
            prop="SkuName"
            :width="tableHeight * 0.22"
            label="物料名称"
            :align="align"
          >
          </el-table-column>
          <el-table-column
            prop="ToCID"
            label="目标托盘"
            :width="tableHeight * 0.15"
            :align="align"
          >
          </el-table-column>
          <el-table-column
            prop="TargetId"
            :width="tableHeight * 0.2"
            label="目标库位"
            :align="align"
            :sort-method="sortByDate"
          >
          </el-table-column>
          <el-table-column
            prop="BatchNo"
            :width="tableHeight * 0.2"
            label="批次号"
            :align="align"
          >
          </el-table-column>
          <el-table-column
            prop="OrderLineNo"
            label="订单行号"
            :width="tableHeight * 0.15"
            :align="align"
          >
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            :width="tableHeight * 0.2"
            :align="align"
          >
            <template slot-scope="scope">
              <el-button
                @click="CompleteClick(scope.row)"
                type="danger"
                :disabled="scope.row.OrderLineStatus === 1 ? false : true"
                style="font-size: 1.5vh"
                >完成任务
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-row>
    <el-link type="primary" style="font-size: 1.5vw"
      >共 {{ length_data }} 条</el-link
    >
    <audioPaly :audioValue="audioPaly"></audioPaly>
  </div>
</template>

<script>
import {
  GETLocationIdsInfo,
  GETLinePatrolPicking,
  postLinePatrolPicking,
} from "@/api/api.js";

import { createSocket } from "@/utils/WebSocket";
import audioPaly from "@/components/pluginunit/audioPaly.vue";
export default {
  components: {
    audioPaly,
  },
  data() {
    return {
      loading: false,
      align: "center",
      tableHeight: 450,
      searchForm: {
        LocationIds: [],
      },
      audioPaly: "",
      LocationIds: [],
      currentPage: 1,
      length_data: 0,
      total: 0,
      pageSize: 20,
      tableData: [],
      print_url: "ws://localhost:13145/Print?UserId=",
      ptl_url: "ws://localhost:13145/Ptl",
      weight_url: "ws://localhost:13145/Weight",
      login_url: "ws://localhost:13145/Login?UserId=",
      ws: {
        print_ws: null,
        ptl_ws: null,
        weight_ws: null,
        login_ws: null,
      },
      setIntervalWesocketPush: {
        print_ws: null,
        ptl_ws: null,
        weight_ws: null,
        login_ws: null,
      },
      timer: null,
      ColorEnum: {
        red: 1,
        green: 2,
        blue: 3,
        yellow: 4,
        pink: 5,
        cyan: 6,
        white: 7,
      },
    };
  },
  created() {
    window.removeEventListener("onmessageWS", this.getSocketData);
    this.UserInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    this.init();
    setTimeout(() => {
      this.onSubmit();
    }, 1500);
  },
  methods: {
    getTimerTask_sps() {
      clearTimeout(this.timer);
      this.timer = null;
      this.timer = setTimeout(() => {
        this.onSubmit();
      }, 5000);
    },
    onSubmit() {
      this.loading = true;
      const params = this.searchForm;
      GETLinePatrolPicking(params).then((res) => {
        const result = res.data.data;
        this.length_data = result.length;
        if (res.data.code == 0 && result.length > 0) {
          this.tableData = result;
          var color_ = {};
          for (let i = 0; i < this.tableData.length; i++) {
            color_[this.tableData[i].FromLoc] =
              (color_[this.tableData[i].FromLoc] || 0) + 1;
            this.PTL_Lighting(
              this.tableData[i].FromLoc,
              (color_[this.tableData[i].FromLoc] % 6) + 1,
              this.tableData[i].QtyPlan,
              this.tableData[i].SkuId,
              this.tableData[i].SkuName,
              this.tableData[i].OrderLineNo
            );
          }
        } else {
          // this.getTimerTask_sps();
          this.$message({
            message: res.data.message,
            type: "error",
          });
        }
        this.loading = false;
        this.getTimerTask_sps();
      }).catch(() => {
        this.getTimerTask_sps();
      });
    },
    sortByDate(obj1, obj2) {
      let val1 = obj1.deadline;
      let val2 = obj2.deadline;
      return val1 - val2;
    },
    CompleteClick(row) {
      this.$confirm("确定完成当前任务, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.CompleteTaskButton(row);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    async CompleteTaskButton(row) {
      const params = row;
      params.WbId = this.UserInfo.WbId;
      params.UserId = this.UserInfo.UserId;
      params.time = Date.parse(new Date());
      postLinePatrolPicking(params).then((res) => {
        const result = res.data.data;
        if (res.data.code == 0) {
          this.$message({
            message: "拣货成功！",
            type: "success",
          });
          this.onSubmit();
          this.audioPaly("success");
        } else {
          this.$message({
            message: res.data.message,
            type: "error",
          });
          this.audioPaly("error");
        }
      });
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.onSubmit();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.onSubmit();
    },
    resetForm() {
      this.searchForm = {
        LocationIds: [],
      };
    },
    WHAreainfo() {
      const params = {};
      GETLocationIdsInfo(params).then((res) => {
        const result = res.data.data;
        if (res.data.code == 0) {
          this.LocationIds = result;
        } else {
          this.$message({
            message: res.data.message,
            type: "error",
          });
          this.audioPaly("error");
        }
      });
    },
    async init(socket_type = true) {
      console.log("init------>>>", socket_type);
      if (socket_type === true || socket_type === "ptl_ws") {
        this.ws.ptl_ws = null;
        this.ws.ptl_ws = new WebSocket(this.ptl_url);
        this.ws.ptl_ws.currSocketId = "ptl_ws";
        this.ws.ptl_ws.currSocketName = "库位灯程序";
        this.ws.ptl_ws.onopen = this.ws_connect;
        this.ws.ptl_ws.onmessage = this.PtlOnMessage;
        this.ws.ptl_ws.onclose = (e) => {
          console.log("库位灯关闭连接");
          clearInterval(
            this.setIntervalWesocketPush[e.currentTarget.currSocketId]
          );
        };
        this.ws.ptl_ws.onerror = this.ws_error;
      }
    },
    ws_error(e) {
      this.onerrorWS(e.currentTarget);
    },
    onerrorWS(ws) {
      clearInterval(this.setIntervalWesocketPush[ws.currSocketId]);
      console.log(ws.currSocketName + "连接失败重连中");
      if (ws.readyState !== 3) {
        this.init(ws.currSocketId);
      }
    },
    ws_connect(e) {
      console.log("websockt已建立", e);
      this.sendPing(e.currentTarget);
    },
    ws_connect_login() {
      if (this.ws.login_ws.readyState === 1) {
        var command = {
          RemoteUrl: this.UserInfo.RemoteUrl,
        };
        this.ws.login_ws.send(JSON.stringify(command));
      } else {
        setTimeout(() => {
          this.ws_connect_login();
        }, 1500);
      }
    },
    sendPing(ws, time = 5000, ping = "客户端发送服务端成功.....") {
      console.log(ws.currSocketName + "客户端发送服务端成功......");
      clearInterval(this.setIntervalWesocketPush[ws.currSocketId]);
      this.setIntervalWesocketPush[ws.currSocketId] = setInterval(() => {
        ws.send(ping);
      }, time);
    },
    PtlOnMessage(e) {
      // 创建接收消息函数
      const data = JSON.parse(e && e.data);
      console.log("服务端向客户端回传信号",data, data.Data.Tag, data.Type);
      if (data.Type === "PTL_Lighting") {
        console.log("PTL_Lighting", data);
      } else if (data.Type === "PTL_Close") {
        console.log("PTL_Close", data);
      } else if (data.Type === "PTL_OFF") {
        /**U2FsdGVkX1/DNnGkNadLEJVDFBLHOahsDSXyEljckNkhZSsaiy2saJfwBcZdNF6B
        vq1floabzirFv8axeF1j2+qsDjYAZIRdz5uVnB00PG1wZvN/1Hn7WOju1xBUnB4V
        joEBFuzCExMxh/OmTJhtWOqUe7h2L+/KCZreP15MYJaJyTMwpEekCRp5dSECJ9ku
        yUKEt+OyPdDVyJKQ2Eq43rchs2IvfEIhkbArgiwr9rEYZnBDb1DEse9hFkucBALr
        iOcxT9JTRSIbDQ==*/
        for (let i = 0; i < this.tableData.length; i++) {
          console.log(
            "PTL_Close1111",
            data.Data.Tag,
            this.tableData[i].FromLoc,
            parseInt(data.Data.Num),
            parseInt(this.tableData[i].QtyPlan)
          );
          if (
            data.Data.Tag === this.tableData[i].FromLoc &&
            parseInt(data.Data.Num) == parseInt(this.tableData[i].QtyPlan)
          ) {
            console.log("PTL_Close2222", this.tableData[i].OrderLineStatus);
            if (this.tableData[i].OrderLineStatus === 1) {
              console.log("PTL_Close3333 this.loading", this.loading);
              if (!this.loading) {
                console.log("PTL_Close关灯");
                this.tableData[i].OrderLineStatus = 0;
                this.CompleteTaskButton(this.tableData[i]);
                this.PTL_Close(data.Data.Tag);
              } else {
                console.log("PTL_Close亮灯");
                // this.audioPaly('error')
                this.PTL_Lighting(
                  this.tableData[i].FromLoc,
                  this.ColorEnum.green,
                  this.tableData[i].QtyPlan,
                  this.tableData[i].SkuId,
                  this.tableData[i].SkuName,
                  this.tableData[i].OrderLineNo
                );
              }
            }
            break;
          }
        }
      } else {
        this.$message({
          type: "error",
          message: "WET消息错误",
        });
      }
    },
    audioPlay(value) {
      this.audioPaly = value;
      setTimeout(() => {
        this.audioPaly = "";
      }, 10);
    },
    async PTL_Lighting(
      LocationId,
      Color,
      QtyPlan,
      SkuId,
      SkuName,
      OrderLineNo
    ) {
      var timeId = new Date().getTime().toString();
      const params = {
        Id: OrderLineNo.toString() + "_" + timeId,
        Type: "PTL_Lighting",
        Data: {
          Tag: LocationId,
          Num: QtyPlan.toString(),
          Mode: "1",
          Color: Color,
          Updown: "2",
          Locator: "",
          Message: SkuId.toString() + "^" + SkuName.toString(),
          PressOff: "1",
        },
      };
      this.ws.ptl_ws.send(JSON.stringify(params));
    },

    async PTL_Close(LocationId) {
      const params = {
        Id: new Date().getTime().toString(),
        Type: "PTL_Close",
        Data: {
          Tag: LocationId,
        },
      };
      this.ws.ptl_ws.send(JSON.stringify(params));
    },
  },
  beforeDestroy() {
    clearTimeout(this.timer); // 清除
    //离开页面移除监听器页面销毁时，移除监听器，这样就不会导致重复监听。
    for (key in this.ws) {
      if (key !== null) {
        key.close();
      }
    }
  },
  watch: {
    searchVal: function (val) {
      console.log(val); // 接收父组件的值
      this.WindowsSize = val;
    },
  },
  mounted() {
    let that = this;
    this.$nextTick(() => {
      //窗口高度 - 表格距离顶部距离 - 需求高度
      this.tableHeight =
        window.innerHeight - this.$refs.tableRef.$el.offsetTop - 100;
      this.$refs.tableRef.doLayout(); // 更新表格 防止表格内容变化表格异常情况
      // 监听窗口大小变化
      window.onresize = function () {
        that.tableHeight =
          window.innerHeight - that.$refs.tableRef.$el.offsetTop - 90;
        that.$refs.tableRef.doLayout();
      };
    });
  },
};
</script>

<style lang="scss">
.search-form {
  // padding-top: 18px;
  // margin-bottom: 15px;
  background-color: #f7f8fb;

  .el-form-item__label {
    font-size: 11px !important;
  }

  display: flex;
}
</style>
